<?php
namespace app\atxunda\controller;
use think\Controller;
use think\Db; 
use think\Request;

class Role extends Common
{
	/**
	 * [index 角色管理]
	 * @return [type] [description]
	 */
	public function index(){
		$data = Db::table('role')->select();
		$this->assign('data',$data);
		return $this->fetch('index');
	}


	/**
	 * [add 添加角色]
	 */
	public function add(){
		if(input('post.')){
			$data = input('post.');
			if(Db::table('role')->insert($data)){
				$this->success('添加成功','index','',1);
			}else{
				$this->error('添加失败');
			}
		}else{
			return $this->fetch('add');
		}
	}

	/**
	 * [edit 编辑角色]
	 * @return [type] [description]
	 */
	public function edit(){
		$request = Request::instance();
		$role_id = $request->param('role_id');
		if(input('post.')){
			$data = input('post.');
			if(Db::table('role')->where('role_id',$role_id)->update($data)){
				$this->success('编辑成功','index','',1);
			}else{
				$this->error('编辑失败');
			}
		}else{
			$role_data = Db::table('role')->where('role_id',$role_id)->find();
			$this->assign('role_data',$role_data);
			return $this->fetch('edit');
		}
	}


	public function delete(){
		$request = Request::instance();
		$role_id = $request->param('role_id');
		if(Db::table('role')->delete($role_id)){
			$this->success('删除成功','index','',1);
		}else{
			$this->error('删除失败');
		}
	}

	public function privilege(){
		$request = Request::instance();
		$role_id = $request->param('role_id');
		if(input('post.')){
			$role_id = input('post.role_id');
			$rp_data = Db::table('role_privilege')->where('role_id',$role_id)->select();
			if($rp_data){
				Db::table('role_privilege')->where('role_id',$role_id)->delete();
			}
			$privilege_ids = input('post.privilege_id/a');
	  		foreach ($privilege_ids as $key => $id) {
	  			$arr[] = array('role_id'=>$role_id,'privilege_id'=>$id);
	  		}
	  		if(\app\atxunda\model\RolePrivilege::getSave($arr)){
	  			$this->success('分配权限成功','index','',1);
	  		}else{
	  			$this->error('分配权限失败',url('privilege',['role_id'=>$role_id]));
	  		}
		}else{
			$role_data = Db::table('role')->field('role_name')->where('role_id',$role_id)->find();
			$data = \app\atxunda\model\Privilege::getPri();
			$rp_data = Db::table('role_privilege')->field('privilege_id')->where("role_id=$role_id")->select();
			$arr = array();
			foreach ($rp_data as $key => $v) {
				$arr[] = $v['privilege_id'];
			}
			$this->assign('arr',$arr);
			$this->assign('data',$data);
			$this->assign('role_id',$role_id);
			$this->assign('role_name',$role_data['role_name']);
			return $this->fetch();
		}
	}
}